package io.dy.task;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author dmj
 * @date 2024年03月02日 下午8:28
 */
public class CompletableDemo {

    public static void main(String[] args) {
        List<MockTask> taskList = IntStream.range(0, 10).mapToObj(i -> new MockTask(1)).collect(Collectors.toList());

        ExecutorService executor = Executors.newFixedThreadPool(10);

        long startTime = System.currentTimeMillis();
        List<CompletableFuture<Integer>> futureList
                = taskList.stream().map(task -> CompletableFuture.supplyAsync(task::doWork, executor)).collect(Collectors.toList());

        List<Integer> time = futureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
        long endTime = System.currentTimeMillis();

        System.out.printf("processes %d task cost %.2f s", time.size(), (endTime - startTime)/1000.0);
    }
}
